﻿using StackExchange.Redis;
using System;

namespace InternetSpiderLib
{
    public class RedisUrlLock : IUrlLock
    {
        public string RedisConnectionString { get; set; }

        public bool IsLockedUrl(string url)
        {
            var lockKey = GetUrlLockKey(url);

            using (ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect(RedisConnectionString))
            {
                var databse = redisClient.GetDatabase();

                return databse.LockQuery(lockKey).IsNull == false;
            }
        }

        public bool LockUrl(string url, int second = 120)
        {
            var lockKey = GetUrlLockKey(url);

            //if (IsLockedUrl(url))
            //{
            //    Console.WriteLine("尝试锁定前，请确定无锁 " + lockKey);
            //    Console.ReadLine();
            //}

            using (ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect(RedisConnectionString))
            {
                var databse = redisClient.GetDatabase();

                return databse.LockTake(lockKey, "", TimeSpan.FromSeconds(second));
            }
        }

        public bool UnLockUrl(string url)
        {
            var lockKey = GetUrlLockKey(url);
            using (ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect(RedisConnectionString))
            {
                var databse = redisClient.GetDatabase();
                return databse.LockRelease(lockKey, "");
            }
        }

        private string GetUrlLockKey(string url)
        {
            return $"NetSpiderUrlLock:Url_{url?.ToLower()}";
        }
    }
}
